﻿using Kz.Telegram.Bot.Console.Demo;
using Kz.Telegram.Bot.Console.HandleUpdate.Enums;
using Kz.Telegram.Bot.Console.HandleUpdate.Models;
using Kz.Telegram.Bot.Infrastructure.Extensions;
using System.Text;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;

namespace Kz.Telegram.Bot.Console.HandleUpdate
{
    public class CallbackQueryHandler : IHandler
    {
        public readonly static InlineKeyboardButton[] InlineSearchFilterButtons = [
            InlineKeyboardButton.WithCallbackData("📢",CallbackQueryModel.Create(InlineCallbackEnum.SearchTypeFilter,"Channel")),
            InlineKeyboardButton.WithCallbackData("👥",CallbackQueryModel.Create(InlineCallbackEnum.SearchTypeFilter,"Supergroup")),
            InlineKeyboardButton.WithCallbackData("🎬",CallbackQueryModel.Create(InlineCallbackEnum.SearchTypeFilter,"Movie")),
            InlineKeyboardButton.WithCallbackData("🖼",CallbackQueryModel.Create(InlineCallbackEnum.SearchTypeFilter,"Picture")),
        ];

        public async Task Handle(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
        {
            var callback = update.CallbackQuery!;
            var data = callback.Data ?? throw new ArgumentNullException("Data 为空");

            var model = data.ToObj<CallbackQueryModel>();

            switch (model.Type)
            {
                case InlineCallbackEnum.JumpManageMenu:
                    break;
                case InlineCallbackEnum.Unmute:
                    {
                        //可入库处理查询，不需要每条信息调用BotAPI
                        var admins = await botClient.GetChatAdministrators(callback.Message!.Chat.Id, cancellationToken);
                        if (!admins.Any(w => w.User.Id == callback.From!.Id))
                        {
                            await botClient.AnswerCallbackQuery(callbackQueryId: callback.Id, text: "⚠️仅限管理员操作！", showAlert: true, cancellationToken: cancellationToken);
                            return;
                        }

                        var chatId = callback.Message.Chat.Id;
                        var userId = callback.Message.Entities![0].User!.Id;

                        await botClient.PromoteChatMember(chatId, userId, canPostMessages: true, cancellationToken: cancellationToken);

                        await botClient.EditMessageText(
                            chatId: chatId,
                            messageId: callback.Message.MessageId,
                            parseMode: ParseMode.Html,
                            linkPreviewOptions: new LinkPreviewOptions() { IsDisabled = true },
                            //disableWebPagePreview: true,
                            text: $"{callback.Message.Text}\r\n已解禁",
                            replyMarkup: null,
                            cancellationToken: cancellationToken);
                    }
                    break;
                case InlineCallbackEnum.SearchFilpPage:
                    {
                        if (callback.From.Id != callback.Message.ReplyToMessage.From.Id)  //必须搜索者操作
                        {
                            await botClient.AnswerCallbackQueryAsync(callbackQueryId: callback.Id, text: "⚠️这不是您的消息！", showAlert: true, cancellationToken: cancellationToken);
                            return;
                        }

                        var keyword = callback.Message!.ReplyToMessage!.Text; //拿到关键字
                        var pageIndex = model.Content.ToInt();

                        var adv = SearchResultList.GetOneAdv();
                        var res = SearchResultList.GetPageResult(out var PageCount, pageIndex);


                        StringBuilder sb = new();
                        sb.AppendLine($"[广告] <a href='{adv.Url}'>{adv.Title}</a>");
                        sb.AppendLine();

                        for (int i = 0; i < res.Count; i++)
                        {
                            sb.AppendLine($"<a href='{res[i].Url}'>{res[i].Title} - {res[i].Total}</a>");
                        }
                        sb.AppendLine();
                        sb.AppendLine("提示：点赞或举报，请点下面数字 👇");


                        var lastPageIndex = pageIndex - 1;    //上一页
                        var nextPageIndex = pageIndex + 1;    //下一页

                        InlineKeyboardMarkup buttons;
                        if (pageIndex == 1)
                        {
                            buttons = new[] {
                                InlineSearchFilterButtons,
                                [
                                    InlineKeyboardButton.WithUrl("😁 购买广告", $"https://t.me/{Bot.UserName}"),
                                    InlineKeyboardButton.WithCallbackData("下一页",CallbackQueryModel.Create(InlineCallbackEnum.SearchFilpPage,nextPageIndex.ToString())
                                    )
                                ]
                            };
                        }
                        else
                        {
                            buttons = new[] {
                                InlineSearchFilterButtons,
                                [
                                    InlineKeyboardButton.WithCallbackData("上一页",CallbackQueryModel.Create(InlineCallbackEnum.SearchFilpPage,lastPageIndex.ToString())),
                                    InlineKeyboardButton.WithCallbackData( "下一页", CallbackQueryModel.Create(InlineCallbackEnum.SearchFilpPage,nextPageIndex.ToString()))
                                ]
                            };
                        }

                        await botClient.EditMessageText(
                            chatId: callback.Message!.Chat.Id,
                            messageId: callback.Message.MessageId,
                            text: sb.ToString(),
                            parseMode: ParseMode.Html,
                            replyMarkup: buttons,
                            linkPreviewOptions: new LinkPreviewOptions() { IsDisabled = true },
                            //disableWebPagePreview: true,
                            cancellationToken: cancellationToken
                        );
                        sb.Clear();

                        break;
                    }
                case InlineCallbackEnum.SendPoll:
                    {
                        await botClient.SendPoll(
                            chatId: callback.Message!.Chat.Id,
                            question: "这是一个投票提问，你是否喜欢18岁的小妹妹",
                            options: ["喜欢", "很喜欢", "必须喜欢"],
                            type: PollType.Regular,
                            allowsMultipleAnswers: false,
                            //closeDate: DateTime.Now.AddSeconds(30),
                            isAnonymous: false,
                            explanation: "asdasdasdadasda",
                            openPeriod: 30,
                            cancellationToken: cancellationToken);
                    }
                    break;
            }
        }
    }
}